/**
 * 项目管理
 */
define(function (require, exports, module) {
    require('authorize');
    var $ = require('jquery');
    var util = require('util');
    var ui = require('ui');
    var angular = require("angular");
    require("angular-route");
    require('angular-interceptor');
    require("angular-ui");
    require("angular-messages");
    require('permission');
    require("pagination");
    require('service/third_channel/channel_service');
    require('global');
    
    var api_prefix = G_CONFIG["api_prefix"] + "qmyx/third-party"; //api前缀
	
    angular.module('channel.controllers', [])
        .constant('limit',10)
        .controller('channelDetailController', [
            '$scope',
            'channelService',
            'limit',
            function ($scope, service,limit) {
                var steps = [
                    {
                        key: "baobei",
                        val: "报备"
                    },
                    {
                        key: "daofang",
                        val: "到访"
                    },
                    {
                        key: "rengou",
                        val: "认购"
                    },
                    {
                        key: "qianyue",
                        val: "签约"
                    }
                ];
                
                $scope.searchObj = util.getQueryParams(location.search);

                $scope.showSets = $scope.searchObj.expand === "1";
                
                var channelId = $scope.searchObj.channelId;

                $scope.toggleSets = function() {
                    $scope.showSets = !$scope.showSets;
                };
                
                $scope.userList = [];
                $scope.status = 1;
                
                $scope.searchUserList = function(pageIndex,status){
                    service.getUserList({
                        search: {
                            channelId: channelId,
                            pageSize: $scope.pager.pageSize || limit,
                            curPage: pageIndex,
                            status: status || $scope.status
                        },
                        success: function (res) {
                            $scope.userList = res.data.items;
                            $scope.pager.total = res.data.total;
                        },
                        fail: function (res) {

                        }
                    });
                };
                
                $scope.pager = {
                    pageSize: limit,
                    change: function(pageIndex){
                        $scope.pager.pageIndex = pageIndex;
                        $scope.searchUserList(pageIndex);
                    }
                };
                
                $scope.getStatisticData = function(){
                    service.getStatisticData({
                        search: {
                            channelId: channelId
                        },
                        success: function (res) {
                            $scope.statisticData = res.data;
                        },
                        fail: function (res) {

                        }
                    });
                };
                
                $scope.statistics = [];
                $scope.statisticData = {
                    "baobei": 0,  //报备数量
                    "daofang": 0, //到访数量
                    "rengou": 0,  //认筹数量
                    "qianyue": 0  //签约数量
                };
                $scope.$watch('statisticData',function(statisticData){
                    if (statisticData) {
                        var statistics = [];
                        
                        for (var i = 0; i < steps.length; i++) {
                            var step = steps[i];
                            statistics.push({
                                id: step.key,
                                name: step.val,
                                count: statisticData[step.key]
                            });
                        }
                        $scope.statistics = statistics;
                    }
                });
                
                $scope.selectStep = function(step) {
                    $scope.step = step;
                };
                
                $scope.step = steps[0].key;
                
                $scope.$watch('step',function(val,old){
                    if (val !== old) {
                        for (var i = 0; i < steps.length; i++) {
                            if (steps[i].key === val) {
                                break;
                            }
                        }
                        $scope.status = i + 1;
                        $scope.searchUserList(1, i+1);
                    }
                });
                
                $scope.getSettingData = function(){
                    service.getSettingData({
                        search: {
                            channelId: channelId
                        },
                        success: function (res) {
                            $scope.setting = res.data;
                            if ($scope.setting && $scope.setting.third_party_info) {
                                $scope.setting.third_party_info.is_open = parseInt($scope.setting.third_party_info.is_open);
                            }

                            var projectIds = [];
                            
                            for (var i = 0; i < res.data.selected_project_list.length; i++) {
                                projectIds.push(res.data.selected_project_list[i].building_id);
                            }
                            $scope.projectIds = projectIds;
                        },
                        fail: function (res) {

                        }
                    })
                };
                
                $scope.getProjectList = function(cb){
                    service.getProjectList({
                        search: {
                            flag:1
                        },
                        success: function (res) {
                            $scope.projectList = res.data;
                            cb && cb();
                        },
                        fail: function (res) {

                        }
                    });
                };
                          
                $scope.saveSetting = function(){
                    var setting = $scope.setting;
                    var data = {
                        channelId: channelId,
                        name: setting.third_party_info.name,
                        phone: setting.third_party_info.phone,
                        contactPerson: setting.third_party_info.contact_person,
                        dayLimit: setting.day_limit.day_limit,
                        partnerId: setting.day_limit.partner_id,
                        projectIdList: $scope.projectIds,
                        isOpen: setting.third_party_info.is_open
                    };
                    service.saveSettings({
                        data: data,
                        success: function (res) {
                            ui.showSucTip("保存成功");
                        },
                        fail: function (res) {
                            //ui.showErrTip("保存失败");
                        }
                    });
                };
                
                $scope.createRuleUrl = "/page/parameter_settings/project.shtml?token=" + $scope.searchObj.token + "#/commission_rules"       
                
                //初始化时获取报备用户列表
                $scope.searchUserList(1, 1);
                
                //获取各状态统计数量
                $scope.getStatisticData();          
                
                //获取项目列表
                $scope.getProjectList(function(){              
                    //ui-project会缓存数据，这里重置一下
                    $scope.projectIds = [];
                    //获取设置信息
                    $scope.getSettingData();
                });

                $scope.afterChangeOpenStatus = function (newValue, oldValue) {
                    if (!newValue) {
                        util.confirm('关闭合作状态将无法继续报备客户，是否继续【关闭】？', {
                            cancel: function () {
                                $scope.setting.third_party_info.is_open = oldValue;
                                $scope.$applyAsync();
                            }
                        })
                    }
                }
                
            }
        ]);
    
    angular.module('chaanelDetail', [
        'ngUI',
        'ngInterceptor',
        'channel.services', 
        'channel.controllers'
    ]);

    angular.element(document).ready(function(){
        angular.bootstrap(document, ['chaanelDetail']);
    })
})